﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.Biz;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.WebLogic;
using GoodMan.Core.NoticeManager;
using GoodMan.Tool.Framework;
using System.Text;
using GoodMan.Portal.Web.Models;
using GoodMan.Infrastructure.Entities.Contract;

namespace GoodMan.Portal.Web.Controllers
{
    [Warp]
    [ErrorHandle]
    [Compress]
    public class ShopController : SiteBaseController
    {
        //
        // GET: /Shop/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ProductItemView(int id = 0)
        {
            try
            {
                int type = 1;
                var product = ProductBiz.GetProductByIdForView(id);//获取商品信息，包含一级分类
                product.TotalRemain = ProductBiz.GetProductRemain(id);
                product.SaleCount = OrderBiz.GetProductSaleCount(product.Id);
                product.Integral = Convert.ToInt32(product.policy.Price * SupportBiz.GetCostRank());
                ViewBag.productiId = product.Id;
                ViewBag.product = product;
                var specialPolicy = PolicyBiz.GetSpecialPolicy(id);//获取特卖策略信息
                ViewBag.policy = specialPolicy;
                if (RecommendedBiz.IsRecommended(product.Id))
                {
                    type = 2;
                }
                if (specialPolicy != null)
                {
                    type = 3;
                }
                ViewBag.saleRecord = OrderBiz.GetSaleRecordByProductId(id, 0, 20);//商品交易记录
                ViewBag.appraiselist = AppraiseBiz.GetAppraiseListByProductId(id, 0, 20);//获取上平评价记录
                ViewBag.AreaCode = (int)product.AreaCode;

                ViewBag.Type = type;
                int productRemain = ProductBiz.GetProductRemain(id);
                ViewBag.IsUnderstock = true;
                ViewBag.ProductRemain = productRemain;

                //判断是否显示评价按钮
                //var IsViewAppriaseBtn = 0;
                //if (OrderBiz.IsHasAppraise(product.Id))
                //{
                //    IsViewAppriaseBtn = 1;
                //}
                //ViewBag.IsViewAppriaseBtn = IsViewAppriaseBtn;

                double totalAppraise = 5.0d;
                var Appraises = new Appraise().FindAll(c => c.ProductId == id && c.State == 1);
                if (Appraises != null && Appraises.Any())
                {
                    totalAppraise = Appraises.Average(c => c.AppraiseGrade);
                }
                ViewBag.totalAppraise = Math.Round(totalAppraise, 1);
                string Satisfaction = "100%";
                var googdAppriase = new Appraise().Count(c => c.ProductId == id && c.State == 1 && c.AppraiseGrade >= 2);
                var allApprise = new Appraise().Count(c => c.ProductId == id && c.State == 1);
                if (allApprise != 0)
                {
                    Satisfaction = Math.Round(googdAppriase * 1.0 / allApprise, 4) * 100 + "%";
                }
                ViewBag.Satisfaction = Satisfaction;

                int userRole = 1;
                int DelAuthenticate = 0;
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    string username = System.Web.HttpContext.Current.User.Identity.Name;
                    var user = new User().Find(username);
                    userRole = (int)user.SystemRole;
                    if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.CollegeAdmin)
                    {
                        DelAuthenticate = 1;
                    }
                }
                ViewBag.DelAuthenticate = DelAuthenticate;
                ViewBag.userRole = userRole;

                ViewBag.limitprice = 5;//需要结果配置修改

                if (product.AreaCode == AreaCode.Group)
                {
                    return View("GroupBuyDetail");
                }
                return View();
            }
            catch
            {
                ViewBag.Message = "未找到指定商品。请返回首页从新选择！";
                return View("../Home/error");
            }
        }

        public ActionResult GetFiveRecommended(int type = 0)
        {
            StringBuilder sb = new StringBuilder();
            if (type == 0)
            {
                List<Product> productlist = ProductBiz.GetFiveRecommended();
                if (productlist != null && productlist.Count > 0)
                {
                    foreach (var item in productlist)
                    {
                        string url = "/shop/ProductItemView?id=" + item.Id;
                        sb.Append("<li class=\"media\"><a class=\"pull-left\" href=\"" + url + "\"  target=\"_blank\">");
                        sb.Append("<img class=\"media-object\" style=\"width:66px;height:44px;\" title=\"" + item.ProductName + "\" src=\"" + item.Images + "\"></a>");
                        sb.Append("<div class=\"p-name\"><div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                        sb.Append("<a href=\"" + url + "\" title=\"" + item.ProductName + "\"  target=\"_blank\">" + item.ProductName + "</a><div><span class=\"price\" style=\"color:red;\">&yen;" + item.DefaulSalePrice + "</span></div></div></div></li>");
                    }
                }
            }
            else if (type == 1)
            {
                List<Product> productlist = ProductBiz.GetFiveHot();
                if (productlist != null && productlist.Count > 0)
                {
                    foreach (var item in productlist)
                    {
                        string url = "/shop/ProductItemView?id=" + item.Id;
                        sb.Append("<li class=\"media\"><a class=\"pull-left\" href=\"" + url + "\">");
                        sb.Append("<img class=\"media-object\" style=\"width:66px;height:44px;\" title=\"" + item.ProductName + "\" src=\"" + item.Images + "\"  target=\"_blank\"></a>");
                        sb.Append("<div class=\"p-name\"><div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                        sb.Append("<a href=\"" + url + "\" title=\"" + item.ProductName + "\"  target=\"_blank\">" + item.ProductName + "</a><div><span class=\"price\" style=\"color:red;\">&yen;" + item.DefaulSalePrice + "</span>&nbsp;<span  class=\"muted\" style=\"font-size:12px;\">已售:" + item.SaleCount + "</span></div></div></div></li>");
                    }
                }
            }
            return Content(sb.ToString());
        }

        public ActionResult Appraise(int pid, int appraiseGrade = 5, string appraiseContent = "", int areaCode = 1, int bId = 0)
        {
            var appraise = new Appraise()
            {
                AppraiseContent = appraiseContent,
                AppraiseDate = DateTime.Now,
                AppraiseGrade = appraiseGrade,
                ProductId = pid,
                UserName = System.Web.HttpContext.Current.User.Identity.Name,
                State = 1
            };
            AppraiseBiz.SaveAppraise(appraise);
            if (areaCode == 10)
            {
                //计算商家的评分  每一个等级哪一个最多商家评分就是那一个
                var business = new Business().Find(bId.ToString());
                if (business != null)
                {
                    business.Levels = AppraiseBiz.CalcBusinessAppraise(bId);
                }
                business.PostModify();

                return Redirect("/Shop/FastFoodDetail?d=" + pid);
            }
            else if (areaCode == 4)
            {
                return Redirect("/Shop/PackagesProductsDetail?id=" + pid);
            }
            else
            {
                return Redirect("/Shop/ProductItemView?id=" + pid);
            }
        }

        public ActionResult DelAppraise(int id = 0, int type = 0, int page = 0, int productid = 0, int areaCode = 1)
        {
            AppraiseBiz.DelAppraise(id);
            if (areaCode == 10)
            {
                if (type == 1)
                {
                    return Redirect("/Shop/ProductAppraises?id=" + productid + "&page=" + page);
                }
                else
                {
                    ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                    return View("../Home/error");
                }
            }
            if (areaCode == 0)
            {
                if (type == 0)
                {
                    return Redirect("/Shop/FastFoodDetail?d=" + productid);
                }
                else if (type == 1)
                {
                    return Redirect("/Shop/ProductAppraises?id=" + productid + "&page=" + page);
                }
                else
                {
                    ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                    return View("../Home/error");
                }
            }
            else if (areaCode == 4)
            {
                if (type == 0)
                {
                    return Redirect("/Shop/PackagesProductsDetail?id=" + productid);
                }
                else if (type == 1)
                {
                    return Redirect("/Shop/ProductAppraises?id=" + productid + "&page=" + page);
                }
                else
                {
                    ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                    return View("../Home/error");
                }
            }
            else
            {
                if (type == 0)
                {
                    return Redirect("/Shop/ProductItemView?id=" + productid);
                }
                else if (type == 1)
                {
                    return Redirect("/Shop/ProductAppraises?id=" + productid + "&page=" + page);
                }
                else
                {
                    ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                    return View("../Home/error");
                }
            }
        }

        public ActionResult ProductSaleRecords(int id = 0, int page = 0)
        {
            if (id > 0 && page >= 0)
            {
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.saleRecord = OrderBiz.GetSaleRecordByProductId(id, page, 20);//商品交易记录
                ViewBag.productId = id;
                return View();
            }
            else
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }
        public ActionResult ProductAppraises(int id = 0, int page = 0)
        {
            if (id > 0 && page >= 0)
            {
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.appraiselist = AppraiseBiz.GetAppraiseListByProductId(id, page, 20);
                ViewBag.productId = id;
                double totalAppraise = 5.0d;
                var Appraises = new Appraise().FindAll(c => c.ProductId == id && c.State == 1);
                if (Appraises != null && Appraises.Count > 0)
                {
                    totalAppraise = Appraises.Average(c => c.AppraiseGrade);
                }
                ViewBag.totalAppraise = Math.Round(totalAppraise, 1);
                string Satisfaction = "100%";
                var googdAppriase = new Appraise().Count(c => c.ProductId == id && c.State == 1 && c.AppraiseGrade >= 2);
                var allApprise = new Appraise().Count(c => c.ProductId == id && c.State == 1);
                if (allApprise != 0)
                {
                    Satisfaction = Math.Round(googdAppriase * 1.0 / allApprise, 4) * 100 + "%";
                }
                ViewBag.Satisfaction = Satisfaction;
                int DelAuthenticate = 0;
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    var username = System.Web.HttpContext.Current.User.Identity.Name;
                    var user = new User().Find(username);
                    if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.CollegeAdmin)
                    {
                        DelAuthenticate = 1;
                    }
                }
                ViewBag.DelAuthenticate = DelAuthenticate;

                return View();

            }
            else
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }

        #region 下单流程
        /// <summary>
        /// 直接购买
        /// </summary>
        /// <param name="verNames"></param>
        /// <param name="productid"></param>
        /// <param name="price"></param>
        /// <param name="buycount"></param>
        /// <returns></returns>
        public ActionResult DirectPurchase(string[] verNames, int productid = 0, decimal price = 0, int buycount = 0)
        {
            try
            {
                int productRemain = ProductBiz.GetProductRemain(productid);

                if (productRemain < buycount)//库存不够
                {
                    ViewBag.IsUnderstock = false;
                    ViewBag.ProductRemain = productRemain;
                    ViewBag.Message = "%>_<%  亲，该商品库存不足(您需要" + buycount + "件，我们只有" + productRemain + "件了，我们在辛勤的补货中...";
                    ViewBag.Url = "/Shop/ProductItemView?id=" + productid;
                    return View("../Home/error");
                    // return View("ProductItemView");
                }
                else
                {
                    var product = new Product().Find(productid.ToString());

                    if (product.AreaCode == AreaCode.Integration)
                    {
                        string username = System.Web.HttpContext.Current.User.Identity.Name;
                        var integration = new Integration().Find(username);
                        decimal userIntegration = 0m;
                        if (integration != null)
                        {
                            userIntegration = integration.CostValue;
                        }
                        var policytemp = new Policy().Find(c => c.ProductId == product.Id);
                        if (userIntegration < (policytemp.Price * SupportBiz.GetCostRank()))
                        {
                            ViewBag.Message = "%>_<%  您的积分不足(需要" + Math.Round(policytemp.Price * SupportBiz.GetCostRank(), 0) + "分，你只有" + Math.Round(userIntegration, 0) + "分，多购买，多评论，能获取到更多积分。";
                            ViewBag.Url = "/Shop/ProductItemView?id=" + product.Id;
                            return View("../Home/error");
                        }
                    }
                    if (product.AreaCode == AreaCode.Group)
                    {
                        int salecount = OrderBiz.GetProductSaleCount(product.Id);
                        if (salecount >= product.CapsPeople)
                        {
                            ViewBag.Message = "%>_<%  已超团购上限人数，看看其他商品吧。";
                            ViewBag.Url = "/Shop/ProductItemView?id=" + product.Id;
                            return View("../Home/error");
                        }
                    }
                    //var produtTemp = product;
                    string verValueStr = "";
                    //如果是套餐
                    if (AreaCode.Combination == product.AreaCode)
                    {
                        verValueStr = Request.Form["verValues"].ToString();
                    }
                    else
                    {
                        if (verNames != null && verNames.Length > 0)
                        {
                            foreach (var verName in verNames)
                            {
                                var verValue = Request.Form[verName].ToString();
                                verValueStr = verValueStr + verValue + "，";
                            }
                            if (verValueStr != "" && verValueStr.Length > 0)
                            {
                                verValueStr = "(" + verValueStr.Substring(0, verValueStr.Length - 1) + ")";
                            }
                        }
                    }
                    // produtTemp.ProductName = produtTemp.ProductName;
                    var orderDetailList = new List<OrderDetail>();
                    var policy = PolicyBiz.GetSpecialPolicy(productid);//获取特卖策略信息
                    if (policy == null)
                    {
                        policy = new Policy().Find(c => c.ProductId == productid && c.PolicyType == 1);
                    }
                    var orderDetail = new OrderDetail()
                    {
                        ProductId = product.Id,
                        ProductName = product.ProductName,
                        Num = buycount,
                        Price = policy.Price,
                        verValue = verValueStr,
                        AreaCode = product.AreaCode
                    };
                    orderDetail.productRemain = productRemain;


                    if (product.AreaCode != AreaCode.Integration)
                    {
                        if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
                        {
                            //do nothing
                        }
                        else
                        {
                            HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                            // oCookie.Expires = DateTime.Now.AddHours(3);
                            string tempCart = oCookie.Value.ToString();
                            var tempList = new List<OrderDetail>();
                            tempList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                            if (tempList != null && tempList.Count > 0)
                            {
                                orderDetailList = new List<OrderDetail>();
                                bool flag = true;
                                foreach (var item in tempList)
                                {
                                    var itemTemp = item;
                                    var policyTemp = PolicyBiz.GetSpecialPolicy(item.ProductId);//获取特卖策略信息
                                    if (policyTemp == null)
                                    {
                                        policyTemp = new Policy().Find(c => c.ProductId == item.ProductId && c.PolicyType == 1);
                                    }
                                    itemTemp.Price = policyTemp.Price;
                                    if (item.ProductId == orderDetail.ProductId && item.verValue == orderDetail.verValue)
                                    {
                                        flag = false;
                                        itemTemp.Num = item.Num + orderDetail.Num;
                                    }

                                    var remainTemp = ProductBiz.GetProductRemain(item.ProductId);
                                    itemTemp.productRemain = remainTemp;
                                    orderDetailList.Add(itemTemp);
                                }
                                if (flag)
                                {
                                    orderDetailList.Add(orderDetail);
                                }
                            }

                            var datatemp = orderDetailList.GroupBy(c => c.ProductId);
                            foreach (var numItem in datatemp)
                            {
                                var remainTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).FirstOrDefault().productRemain;
                                var buycountTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).Sum(c => c.Num);
                                if (remainTemp < buycountTemp)
                                {
                                    var produtTemp = new Product().Find(numItem.Key.ToString());
                                    ViewBag.Message = "%>_<%  亲，该商品[" + produtTemp.ProductName + "]库存不足(您需要" + buycountTemp + "件，我们只有" + remainTemp + "件了，我们在辛勤的补货中...";
                                    ViewBag.Url = "/Shop/ProductItemView?id=" + productid;
                                    return View("../Home/error");
                                }
                            }
                        }
                    }
                    if (orderDetailList == null || orderDetailList.Count == 0)
                    {
                        // orderDetail.verValue = "[" + orderDetail.verValue + "*" + orderDetail.Num + "]";
                        orderDetailList.Add(orderDetail);
                    }



                    // ViewBag.TotalMoney = price;
                    ViewBag.areaCode = (int)product.AreaCode;
                    ViewBag.OrderDetails = orderDetailList;
                    string usernameTemp = System.Web.HttpContext.Current.User.Identity.Name;
                    ViewBag.User = new User().Find(usernameTemp);
                    var FloorList = SupportBiz.GetDormitories();
                    ViewBag.FloorList = FloorList;
                }
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("ComfirmOrder");
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, e.Message);
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }

        /// <summary>
        /// 直接购买--快餐
        /// </summary>
        /// <param name="verNames"></param>
        /// <param name="productid"></param>
        /// <param name="price"></param>
        /// <param name="buycount"></param>
        /// <returns></returns>
        public ActionResult DirectPurchaseFastFood(FastFoodModel model)
        {
            try
            {
                var order = new Order();
                var orderDetailList = new List<OrderDetail>();

                decimal totalMoney = 0m;

                var orderDetail = new OrderDetail();
                Product product = new Product().Find(model.ProductId.ToString());
                //获取默认政策
                var policy = new Policy().Find(c => c.ProductId == product.Id && c.PolicyType == 1);

                orderDetail.AreaCode = product.AreaCode;
                orderDetail.Num = model.Number;
                orderDetail.PolicyId = policy.Id;

                orderDetail.ProductId = product.Id;
                orderDetail.ProductName = product.ProductName;
                orderDetail.ProductSubType = 0;
                orderDetail.ProductType = 0;
                order.ProductDescript = "(" + orderDetail.ProductName + ")&nbsp;&nbsp;*&nbsp;&nbsp;" + orderDetail.Num;//点餐名字和数量
                CateringSet cateringSet = new CateringSet();
                if (string.IsNullOrEmpty(product.Catering))
                {
                    orderDetail.Price = policy.Price;
                    totalMoney = policy.Price * orderDetail.Num;
                }
                else
                {
                    //计算配餐信息
                    string[] mainNumber = new string[2];//记录有多少种配菜
                    int step = 0;//记录每个大类有多少个配菜
                    int stepNumber = 0;//记录每个步长跳过的数量
                    decimal totalMoneyTemp = 0m;
                    List<Catering> cateringList = new List<Catering>();
                    bool isExitsCatering = false;
                    for (int i = 0; i < model.MainFood.Length; i++)
                    {
                        Catering catering = new Catering();
                        List<CateringInfo> cateringInfoList = new List<CateringInfo>();
                        mainNumber = model.MainFood[i].Split('|');
                        step = Convert.ToInt32(mainNumber[0]);
                        catering.caterCategory = mainNumber[1];
                        for (int j = 0; j < step; j++)
                        {
                            if (Convert.ToInt32(model.VerNumber[stepNumber + j]) != 0)
                            {
                                CateringInfo cateringInfo = new CateringInfo();
                                cateringInfo.caterName = model.VerName[stepNumber + j];
                                cateringInfo.caterNumber = model.VerNumber[stepNumber + j];
                                cateringInfo.caterPrice = model.VerPrice[stepNumber + j];
                                cateringInfoList.Add(cateringInfo);

                                totalMoneyTemp += (Convert.ToDecimal(cateringInfo.caterPrice) * Convert.ToDecimal(cateringInfo.caterNumber));
                            }
                        }
                        stepNumber += step;
                        catering.cateringInfoList = cateringInfoList;
                        if (cateringInfoList != null && cateringInfoList.Count != 0)
                        {
                            isExitsCatering = true;
                            cateringList.Add(catering);
                        }
                    }
                    cateringSet.cateringList = cateringList;
                    orderDetail.Price = totalMoneyTemp;

                    totalMoney = orderDetail.Price * orderDetail.Num;
                    if (isExitsCatering)
                        orderDetail.Catering = cateringSet.ToJson();// json格式
                    else
                        orderDetail.Catering = "";
                }


                orderDetail.productRemain = 0;
                orderDetailList.Add(orderDetail);
                string name = System.Web.HttpContext.Current.User.Identity.Name;
                User user = new User().Find(name);
                var floor = new Dormitory().Find(user.FloorId.ToString());
                if (floor != null && !string.IsNullOrEmpty(floor.Name))
                {//如果是管理员没有楼栋信息就只记录真实姓名和联系方式
                    order.AssemblingInfo = floor.Name + "   " + user.Dormitory + "     ";
                }
                order.AssemblingInfo += user.RealName + "(电话:" + user.Phone + ")";//配送信息：张三（手机：13100000000） 楼栋 1310

                //获取用户信息
                order.DormitoryID = user.FloorId;
                order.OrderCode = OrderBiz.OrderCodeGenerator(AreaCode.Snack);
                order.OrderDate = DateTime.Now;
                order.Phone = user.Phone;
                order.BusinessId = product.BusinessId;
                order.Remark = "";
                order.Status = OrderStatus.Reserved;
                order.TotalPrice = totalMoney;
                order.UserName = user.UserName;
                order.AreaCode = AreaCode.Snack;

                var orderHistory = new OrderHistory();
                orderHistory.CreateTime = DateTime.Now;
                orderHistory.CurrentStatue = OrderStatus.Reserved;

                ViewBag.Order = order;
                var FloorList = SupportBiz.GetDormitories();
                ViewBag.FloorList = FloorList;
                ViewBag.areaCode = 10;
                ViewBag.OrderDetails = orderDetailList;
                ViewBag.User = new User().Find(System.Web.HttpContext.Current.User.Identity.Name);
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("ComfirmOrder");
            }
            catch
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }


        public ActionResult CartPurchase()
        {
            string username = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(username);
            if (user.SystemRole != UserRole.Member)
            {
                ViewBag.Message = "哦？亲，你不是会员，你不能购买商品。";
                return View("../Home/error");
            }
            try
            {
                var orderDetailList = new List<OrderDetail>();

                if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
                {
                    ViewBag.Message = "哦？您的购物车空了，多多放点进去哦。";
                    return View("../Home/error");
                }
                else
                {
                    HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                    oCookie.Expires = DateTime.Now.AddHours(1);
                    string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                    var tempList = new List<OrderDetail>();
                    tempList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                    orderDetailList = new List<OrderDetail>();

                    foreach (var item in tempList)
                    {
                        var itemTemp = item;
                        var policyTemp = PolicyBiz.GetSpecialPolicy(item.ProductId);//获取特卖策略信息
                        if (policyTemp == null)
                        {
                            policyTemp = new Policy().Find(c => c.ProductId == item.ProductId && c.PolicyType == 1);
                        }
                        itemTemp.Price = policyTemp.Price;

                        var remainTemp = ProductBiz.GetProductRemain(item.ProductId);
                        itemTemp.productRemain = remainTemp;
                        orderDetailList.Add(itemTemp);
                    }


                    var datatemp = orderDetailList.GroupBy(c => c.ProductId);
                    foreach (var numItem in datatemp)
                    {
                        var remainTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).FirstOrDefault().productRemain;
                        var buycountTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).Sum(c => c.Num);
                        if (remainTemp < buycountTemp)
                        {
                            var produtTemp = new Product().Find(numItem.Key.ToString());
                            ViewBag.Message = "%>_<%  亲，该商品[" + produtTemp.ProductName + "]库存不足(您需要" + buycountTemp + "件，我们只有" + remainTemp + "件了，我们在辛勤的补货中...";
                            // ViewBag.Url = "/Shop/ProductItemView?id=" + productid;
                            return View("../Home/error");
                        }
                    }

                }


                ViewBag.areaCode = 1;
                ViewBag.OrderDetails = orderDetailList;
                string name = System.Web.HttpContext.Current.User.Identity.Name;
                ViewBag.User = new User().Find(name);
                var FloorList = SupportBiz.GetDormitories();
                ViewBag.FloorList = FloorList;
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("ComfirmOrder");
            }
            catch
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }

        public ActionResult SubmitOrder()
        {
            ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
            return View("../Home/error");
        }

        [HttpPost]
        public ActionResult SubmitOrder(string productIds, string IntegratIds, int areacode, string remark,
            string userRealName, string phone, string address, int domitory = 0, decimal totalmoney = 0, int intotalmoney = 0)
        {
            try
            {
                var order = new Order();
                var orderDetailList = new List<OrderDetail>();

                string buyDes = "";

                bool isFlag = true;

                if (productIds != null && productIds != "")//处理非积分商品
                {
                    #region 处理非积分商品


                    decimal totalMoneyTemp = 0m;
                    productIds = productIds.Substring(0, productIds.Length - 1);
                    string[] productIdArray = productIds.Split(',');
                    foreach (var item in productIdArray)
                    {
                        string productid = Request.Form["productid" + item].ToString();
                        var orderDetail = new OrderDetail();
                        var product = new Product().Find(productid);
                        int Id = int.Parse(productid);
                        var policy = PolicyBiz.GetSpecialPolicy(Id);//获取特卖策略信息
                        if (policy == null)
                        {
                            policy = new Policy().Find(c => c.ProductId == Id && c.PolicyType == 1);
                        }
                        var num = Request.Form["num" + item].ToString();
                        var verValue = Request.Form["ver" + item].ToString();
                        orderDetail.AreaCode = product.AreaCode;
                        orderDetail.Num = int.Parse(num);
                        orderDetail.PolicyId = policy.Id;
                        orderDetail.Price = policy.Price;
                        orderDetail.ProductId = product.Id;
                        orderDetail.ProductName = product.ProductName;
                        orderDetail.ProductSubType = product.ProductSubType;
                        orderDetail.ProductType = product.ProductType;

                        totalMoneyTemp = totalMoneyTemp + policy.Price * orderDetail.Num;

                        if (verValue.Length > 2)
                        {
                            orderDetail.Remark = verValue.Substring(1, verValue.Length - 2);
                        }
                        int productRemain = ProductBiz.GetProductRemain(Id);

                        orderDetail.productRemain = productRemain;
                        orderDetailList.Add(orderDetail);
                        buyDes = buyDes + product.ProductName + "(" + product.ProductCode + ")" + verValue + "*" + num + "、";
                    }

                    var datatemp = orderDetailList.GroupBy(c => c.ProductId);
                    foreach (var numItem in datatemp)
                    {
                        var remainTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).FirstOrDefault().productRemain;
                        var buycountTemp = orderDetailList.Where(c => c.ProductId == numItem.Key).Sum(c => c.Num);
                        if (remainTemp < buycountTemp)
                        {
                            var produtTemp = new Product().Find(numItem.Key.ToString());
                            ViewBag.Message = "[" + produtTemp.ProductName + "]库存不足。";
                            isFlag = false;
                        }
                    }

                    var floor = new Dormitory().Find(domitory.ToString());
                    order.AssemblingInfo = floor.Name + "   " + address + "     " + userRealName + "(电话:" + phone + ")";//配送信息：张三（手机：13100000000） 楼栋 1310
                    order.DormitoryID = domitory;
                    order.OrderCode = OrderBiz.OrderCodeGenerator((AreaCode)areacode);
                    order.OrderDate = DateTime.Now;
                    order.Phone = phone;
                    order.ProductDescript = buyDes.Substring(0, buyDes.Length - 1);// 所购买的产品简单描述 例：（友友泡凤爪(125g)*2、统一老坛酸菜牛肉面（桶）*1、）格式为产品名称[(规格)]*购买数量
                    order.Remark = "";
                    order.Status = OrderStatus.Reserved;
                    order.TotalPrice = totalMoneyTemp;
                    order.UserName = System.Web.HttpContext.Current.User.Identity.Name;
                    order.AreaCode = AreaCode.Normal;
                    order.HandleUser = "";
                    order.BusinessId = 0;
                    order.Remark = remark;

                    var orderHistory = new OrderHistory();
                    orderHistory.CreateTime = DateTime.Now;
                    orderHistory.CurrentStatue = OrderStatus.Reserved;
                    ViewBag.areaCode = areacode;
                    var orderTemp = OrderBiz.SaveOrder(order, orderDetailList, orderHistory);
                    ViewBag.Order = orderTemp;

                    //清空cookie
                    //HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                    //oCookie.Expires = DateTime.Now.AddDays(-2);
                    //System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);

                    #endregion
                }
                else if (IntegratIds != null && IntegratIds != "")//处理积分商品
                {
                    #region 处理积分商品

                    decimal totalMoneyTemp = 0m;
                    productIds = IntegratIds.Substring(0, IntegratIds.Length - 1);
                    string[] productIdArray = productIds.Split(',');
                    foreach (var productid in productIdArray)
                    {
                        var orderDetail = new OrderDetail();
                        var product = new Product().Find(productid);
                        int Id = int.Parse(productid);

                        var policy = new Policy().Find(c => c.ProductId == Id && c.PolicyType == 1);

                        var num = Request.Form["innum" + productid].ToString();
                        var verValue = Request.Form["inver" + productid].ToString();
                        orderDetail.AreaCode = product.AreaCode;
                        orderDetail.Num = int.Parse(num);
                        orderDetail.PolicyId = policy.Id;
                        orderDetail.Price = policy.Price;
                        orderDetail.ProductId = product.Id;
                        orderDetail.ProductName = product.ProductName;
                        orderDetail.ProductSubType = product.ProductSubType;
                        orderDetail.ProductType = product.ProductType;
                        totalMoneyTemp = totalMoneyTemp + policy.Price * orderDetail.Num;
                        if (verValue.Length > 2)
                        {
                            orderDetail.Remark = verValue.Substring(1, verValue.Length - 2);
                        }
                        int productRemain = ProductBiz.GetProductRemain(Id);
                        if (orderDetail.Num > productRemain)
                        {
                            ViewBag.Message = "[" + product.ProductName + "]库存不足。";
                            isFlag = false;
                        }
                        orderDetailList.Add(orderDetail);
                        buyDes = buyDes + product.ProductName + "(" + product.ProductCode + ")" + verValue + "*" + num + "、";
                    }
                    var floor = new Dormitory().Find(domitory.ToString());
                    order.AssemblingInfo = floor.Name + "   " + address + "     " + userRealName + "(电话:" + phone + ")";//配送信息：张三（手机：13100000000） 楼栋 1310
                    order.DormitoryID = domitory;
                    order.OrderCode = OrderBiz.OrderCodeGenerator((AreaCode)areacode);
                    order.OrderDate = DateTime.Now;
                    order.Phone = phone;
                    order.ProductDescript = buyDes.Substring(0, buyDes.Length - 1);// 所购买的产品简单描述 例：（友友泡凤爪(125g)*2、统一老坛酸菜牛肉面（桶）*1、）格式为产品名称[(规格)]*购买数量
                    order.Remark = "";
                    order.Status = OrderStatus.Reserved;
                    order.TotalPrice = totalMoneyTemp;
                    order.UserName = System.Web.HttpContext.Current.User.Identity.Name;
                    order.AreaCode = AreaCode.Integration;
                    order.HandleUser = "";
                    order.BusinessId = 0;
                    order.Remark = remark;

                    var orderHistory = new OrderHistory();
                    orderHistory.CreateTime = DateTime.Now;
                    orderHistory.CurrentStatue = OrderStatus.Reserved;
                    ViewBag.areaCode = areacode;
                    var orderTemp = OrderBiz.SaveOrder(order, orderDetailList, orderHistory);

                   // orderTemp.TotalPrice = orderTemp.TotalPrice * SupportBiz.GetCostRank();
                    ViewBag.Order = orderTemp;
                    #endregion
                }
                ViewBag.remark = remark;
                if (!isFlag)
                {

                    ViewBag.areaCode = areacode;
                    ViewBag.OrderDetails = orderDetailList;
                    string name = System.Web.HttpContext.Current.User.Identity.Name;
                    ViewBag.User = new User().Find(name);
                    var FloorList = SupportBiz.GetDormitories();
                    ViewBag.FloorList = FloorList;
                    ViewBag.limitprice = 5;//需要结果配置修改
                    return View("ComfirmOrder");
                }
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("PayOrder");

            }
            catch
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }


        [HttpPost]
        public ActionResult SubmitOrderFastFood(FastFoodModel model, string remark)
        {
            try
            {
                var order = new Order();
                var orderDetailList = new List<OrderDetail>();
                var orderDetail = new OrderDetail();
                Product product = new Product().Find(model.ProductId.ToString());
                //获取默认政策
                var policy = new Policy().Find(c => c.ProductId == product.Id && c.PolicyType == 1);

                orderDetail.AreaCode = product.AreaCode;
                orderDetail.Num = model.Number;
                orderDetail.PolicyId = policy.Id;
                orderDetail.ProductId = product.Id;
                orderDetail.ProductName = product.ProductName;
                orderDetail.ProductSubType = 0;
                orderDetail.ProductType = 0;
                order.ProductDescript = "(" + orderDetail.ProductName + ") * " + orderDetail.Num;//点餐名字和数量
                CateringSet cateringSet = new CateringSet();
                orderDetail.Price = model.Money; //因为订单表和订单详情都只有一条数据，因此该价格就是总价                         

                orderDetail.Catering = model.Catering;

                orderDetail.productRemain = 0;
                orderDetailList.Add(orderDetail);
                string name = System.Web.HttpContext.Current.User.Identity.Name;
                User user = new User().Find(name);
                var floor = new Dormitory().Find(user.FloorId.ToString());
                if (floor != null && !string.IsNullOrEmpty(floor.Name))
                {//如果是管理员没有楼栋信息就只记录真实姓名和联系方式
                    order.AssemblingInfo = floor.Name + "   " + user.Dormitory + "     ";
                }
                order.AssemblingInfo += user.RealName + "(电话:" + user.Phone + ")";//配送信息：张三（手机：13100000000） 楼栋 1310

                //获取用户信息
                order.DormitoryID = user.FloorId;
                order.OrderCode = OrderBiz.OrderCodeGenerator(AreaCode.Snack);
                order.OrderDate = DateTime.Now;
                order.Phone = user.Phone;
                order.BusinessId = product.BusinessId;
                order.Remark = remark;
                order.Status = OrderStatus.Reserved;
                order.TotalPrice = orderDetail.Price;
                order.UserName = user.UserName;
                order.AreaCode = AreaCode.Snack;

                var orderHistory = new OrderHistory();
                orderHistory.CreateTime = DateTime.Now;
                orderHistory.CurrentStatue = OrderStatus.Reserved;
                var orderTemp = OrderBiz.SaveOrder(order, orderDetailList, orderHistory);
                ViewBag.Order = orderTemp;
                var FloorList = SupportBiz.GetDormitories();
                ViewBag.FloorList = FloorList;
                ViewBag.areaCode = 10;
                ViewBag.OrderDetails = orderDetailList;
                ViewBag.User = new User().Find(System.Web.HttpContext.Current.User.Identity.Name);

                ViewBag.remark = remark;
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("PayOrder");

            }
            catch
            {
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }

        public ActionResult UserCenterPay(int Id = 0)
        {
            var order = new Order().Find(Id.ToString());
            if (order == null)
            {
                ViewBag.Message = "您要支付的订单不存在。";
                ViewBag.Url = "/usercenter/order";
                return View("../Home/error");

            }
            else
            {
                 
                ViewBag.Order = order;
                ViewBag.areaCode = (int)order.AreaCode;
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("PayOrder");
            }


        }

        public ActionResult PayOrder()
        {
            ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
            return View("../Home/error");
        }

        [HttpPost]
        public ActionResult PayOrder(int orderId, int payType = 2)
        {
            try
            {
                if (payType == 3)
                { string username = System.Web.HttpContext.Current.User.Identity.Name;
                        var integration = new Integration().Find(username);
                        decimal userIntegration = 0m;
                        if (integration != null)
                        {
                            userIntegration = integration.CostValue;
                        }
                       
                    var order = new Order().Find(orderId.ToString());
                   // var policytemp = new Policy().Find(c => c.ProductId == product.Id);
                    if (userIntegration < (order.TotalPrice * SupportBiz.GetCostRank()))
                    {
                        ViewBag.Message = "%>_<%  您的积分不足(需要" + Math.Round(order.TotalPrice * SupportBiz.GetCostRank(), 0) + "分，你只有" + Math.Round(userIntegration, 0) + "分，多购买，多评论，能获取到更多积分。";
                       // ViewBag.Url = "/Shop/ProductItemView?id=" + product.Id;
                        return View("../Home/error");
                    }
                    else
                    {
                        OrderBiz.DealIntegral(order.UserName, (int)(order.TotalPrice * SupportBiz.GetCostRank()), false);
                    }
                }

                if (payType == 2 || payType == 3)
                {
                    var order = new Order().Find(orderId.ToString());
                    order.Status = OrderStatus.WaitForDeliver;
                    order.PostModify();
                    // OrderBiz.ModifyOrderStatus(orderId, (int)OrderStatus.WaitForDeliver);
                    OrderBiz.ModifyOrderPayWay(orderId, (int)PayWay.Cash);
                }
                else
                {
                    // OrderBiz.ModifyOrderStatus(orderId, (int)OrderStatus.Paid);
                    var order = new Order().Find(orderId.ToString());
                    order.Status = OrderStatus.Paid;
                    order.PostModify();
                    OrderBiz.ModifyOrderPayWay(orderId, (int)PayWay.Online);
                }

               

                var orderHistory = new OrderHistory();
                orderHistory.OrderId = orderId;
                orderHistory.CreateTime = DateTime.Now;
                orderHistory.PreStatus = OrderStatus.Reserved;
                if (payType == 2 || payType == 3)//货到付款 3积分兑换
                {
                    orderHistory.CurrentStatue = OrderStatus.Paid;
                    orderHistory.Remark = "货到付款";
                    orderHistory.PostAdd();
                    orderHistory.PreStatus = OrderStatus.Paid;
                    orderHistory.CurrentStatue = OrderStatus.WaitForDeliver;
                    orderHistory.PostAdd();
                    SupportBiz.DoNotice(orderId);
                }
                else if (payType == 1)//在线支付
                {
                    orderHistory.CurrentStatue = OrderStatus.Paid;
                    orderHistory.Remark = "在线支付";
                    orderHistory.PostAdd();
                }


                ViewBag.order = new Order().Find(orderId.ToString());
                ViewBag.OrderId = orderId;
                ViewBag.limitprice = 5;//需要结果配置修改
                return View("BuyComplete");
            }
            catch (Exception ex)
            {
                //LogHelper.Write(CommonLogger.ExServer, LogLevel.Trace, ex);
                ViewBag.Message = "对不起，出错了！请稍后重试或联系管理员。";
                return View("../Home/error");
            }
        }

        #endregion

        #region 购物车

        public ActionResult AddProductToCart(string verNames, string verValues, int productid = 0, int buycount = 0)
        {

            var product = new Product().Find(productid.ToString());

            string verValueStr = "";
            if (verValues != null && verValues.Length > 0)
            {
                string[] verValTemps = verValues.Split(',');
                foreach (var verValue in verValTemps)
                {
                    if (verValue != "")
                    {
                        //var verValue = Request.Form[verName].ToString();
                        verValueStr = verValueStr + verValue + "，";
                    }
                }
                if (verValueStr != "" && verValueStr.Length > 0)
                {
                    verValueStr = "(" + verValueStr.Substring(0, verValueStr.Length - 1) + ")";
                }
            }


            var policy = PolicyBiz.GetSpecialPolicy(productid);
            if (policy == null)
            {
                policy = new Policy().Find(c => c.ProductId == productid && c.PolicyType == 1);
            }

            var OrderDetail = new OrderDetail()
            {
                ProductId = product.Id,
                ProductName = product.ProductName,
                Num = buycount,
                Price = policy.Price,
                verValue = verValueStr,
                AreaCode = product.AreaCode
            };
            var orderDetailList = new List<OrderDetail>();
            if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
            {
                orderDetailList.Add(OrderDetail);
                string orderDetailListstr = orderDetailList.ToJson();

                //LogHelper.Write(CommonLogger.System, LogLevel.Trace, "第1次加入：" + orderDetailListstr);

                HttpCookie oCookie = new HttpCookie("ShoppingCart");

                oCookie.Expires = DateTime.Now.AddHours(3);
                oCookie.Value = HttpUtility.UrlEncode(orderDetailListstr, Encoding.GetEncoding("UTF-8"));

                System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                oCookie.Expires = DateTime.Now.AddHours(1);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                var tempList = new List<OrderDetail>();
                tempList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                if (tempList != null && tempList.Count > 0)
                {
                    bool flag = true;
                    foreach (var item in tempList)
                    {
                        var itemTemp = item;
                        if (item.ProductId == OrderDetail.ProductId && item.verValue == OrderDetail.verValue)
                        {
                            flag = false;
                            itemTemp.Num = item.Num + OrderDetail.Num;

                        }
                        orderDetailList.Add(itemTemp);
                    }
                    if (flag)
                    {
                        orderDetailList.Add(OrderDetail);
                    }
                    // LogHelper.Write(CommonLogger.System, LogLevel.Trace, "第N次加入：" + orderDetailList.ToJson());
                    oCookie.Value = HttpUtility.UrlEncode(orderDetailList.ToJson(), Encoding.GetEncoding("UTF-8"));
                    System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
                }

            }
            //

            return Content(convertToHtml(orderDetailList));
        }

        public ActionResult RemoveShoppingCart(int ProductID = 0, string verValue = "")
        {
            var orderDetailList = new List<OrderDetail>();
            if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
            {
                //Do nothing
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                oCookie.Expires = DateTime.Now.AddHours(3);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                var tempList = new List<OrderDetail>();
                tempList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                if (tempList != null && tempList.Count > 0)
                {

                    foreach (var item in tempList)
                    {
                        var itemTemp = item;
                        if (item.ProductId == ProductID && item.verValue == verValue)
                        {
                            continue;
                        }
                        orderDetailList.Add(itemTemp);
                    }
                    oCookie.Value = HttpUtility.UrlEncode(orderDetailList.ToJson(), Encoding.GetEncoding("UTF-8"));
                    System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
                }
            }

            return Content(convertToHtml(orderDetailList));
        }

        public ActionResult ChangeProductNum(int prodductid = 0, string verValue = "", int num = 1)
        {
            List<OrderDetail> orderDetailList = null;
            if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
            {
                //Do nothing
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                oCookie.Expires = DateTime.Now.AddHours(1);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                var tempList = new List<OrderDetail>();
                tempList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                if (tempList != null && tempList.Count > 0)
                {
                    orderDetailList = new List<OrderDetail>();
                    foreach (var item in tempList)
                    {
                        var itemTemp = item;
                        if (item.ProductId == prodductid && item.verValue == verValue)
                        {
                            itemTemp.Num = num;
                        }
                        orderDetailList.Add(itemTemp);
                    }
                    oCookie.Value = HttpUtility.UrlEncode(orderDetailList.ToJson(), Encoding.GetEncoding("UTF-8"));
                    System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
                }
            }
            return Content(convertToHtml(orderDetailList));
        }

        public ActionResult ClearShoppingCart()
        {
            if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
            {
                //Do nothing
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                oCookie.Expires = DateTime.Now.AddDays(-2);
                System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);

            }
            return Content(convertToHtml(null));
        }

        public string convertToHtml(List<OrderDetail> detailList)
        {
            decimal limitprice = 5;//需要替换为动态
            StringBuilder sb = new StringBuilder();
            sb.Append("<table class=\"table table-x\" ><thead><tr><th>商品名称</th><th style=\"width:15%;\">单价（元）</th><th style=\"width:15%;\">数量</th><th style=\"width:15%;\">小计（元）</th><th style=\"width:15%;\"></th></tr></thead><tbody>");
            decimal totalmoney = 0m;
            int j = 0;
            if (detailList != null && detailList.Any())
            {
                j = 1;
                string ids = "";
                foreach (var item in detailList)
                {
                    decimal money = item.Price * item.Num;
                    totalmoney = totalmoney + money;
                    ids = ids + j + ",";

                    sb.Append("<tr><td>");
                    sb.Append(item.ProductName + item.verValue);
                    sb.Append("<input type=\"hidden\" name=\"vercart" + j + "\" id=\"vercart" + j + "\" value=\"" + item.verValue + "\" /></td>");
                    sb.Append("<td>&yen;" + item.Price + "</td><td>");
                    sb.Append("<input style=\"width:30px; text-align:center;\" type=\"text\" id=\"numcart" + j + "\" name=\"numcart" + j + "\" value=\"" + item.Num + "\" onkeyup=\"changeCartNum(" + j + "," + item.Price + "," + item.ProductId + ")\" /></td>");
                    sb.Append("<td  style=\"text-align: center; color: #DC143C;\">&yen;<span id=\"moneycart" + j + "\" name=\"moneycart" + j + "\">" + money + "</span></td>");
                    sb.Append("<td ><button onclick=\"DelShoppingCart(" + item.ProductId + ",'" + item.verValue + "')\" class=\"btn btn-danger btn-mini\" >删除</button></td></tr>");

                    j++;
                }
                sb.Append("<input type=\"hidden\" id=\"ids\" name=\"ids\" value=\"" + ids + "\" />");

                sb.Append("</tbody><tfoot><tr><th><div class=\"text-lef\"><button onclick=\"ClearShoppingCart()\" class=\"btn btn-danger\">清空购物车</button></div></th>");
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    sb.Append("<th colspan=\"4\"><div class=\"text-right\">商品总价：<strong class=\"red text-large\">&yen;<span id=\"totalmoneycart\">" + totalmoney + "</span></strong><br /><br /><a href=\"/shop/CartPurchase\" class=\"btn btn-danger\"><span class=\"icon-white icon-ok\"></span>&nbsp;确定购买</a></div></th></tr><tr><td colspan=\"3\"><span style=\"color:red;\">如果购物不足" + limitprice + "元，请自行前往楼栋售货员处提货并付款。</span></td></tr></tfoot></table>");
                }
                else
                {
                    string loginUrl = "/account/login?returnurl=" + System.Web.HttpContext.Current.Server.UrlEncode("/shop/CartPurchase");
                    sb.Append("<th colspan=\"4\"><div class=\"text-right\">商品总价：<strong class=\"red text-large\">&yen;<span id=\"totalmoneycart\">" + totalmoney + "</span></strong><br /><br /><a href=\"" + loginUrl + "\" class=\"btn btn-danger\"><span class=\"icon-white icon-ok\"></span>&nbsp;确定购买</a></div></th></tr><tr><td colspan=\"3\"><span style=\"color:red;\">如果购物不足" + limitprice + "元，请自行前往楼栋售货员处提货并付款。</span></td></tr></tfoot></table>");
                }
            }
            else
            {
                sb.Append("</tbody><tfoot><tr><th><div class=\"text-lef\"><button onclick=\"ClearShoppingCart()\" class=\"btn btn-danger\">清空购物车</button></div></th>");

                sb.Append("<th colspan=\"4\"><div class=\"text-right\">商品总价：<strong class=\"red text-large\"><span id=\"totalmoneycart\">&yen;" + totalmoney + "</span></strong><br /><br /><button class=\"btn btn-danger\" disabled=\"disabled\"><span class=\"icon-white icon-ok\"></span>&nbsp;确定购买</button></div></th></tr><tr><td colspan=\"3\"><span style=\"color:red;\">如果购物不足" + limitprice + "元，请自行前往楼栋售货员处提货并付款。</span></td></tr></tfoot></table>");
            }
            return sb.ToString() + "^" + (j > 0 ? j - 1 : j);
        }

        public ActionResult GetShoppingCart()
        {

            List<OrderDetail> orderDetailList = null;
            if (System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
            {
                //Do nothing
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["ShoppingCart"];
                oCookie.Expires = DateTime.Now.AddHours(1);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                orderDetailList = new List<OrderDetail>();
                orderDetailList = TypePlug.ToObject<List<OrderDetail>>(tempCart);
                // LogHelper.Write(CommonLogger.System, LogLevel.Trace, "获取：" + tempCart);
            }
            return Content(convertToHtml(orderDetailList));
        }

        #endregion

        #region 前台商品分区列表
        public ActionResult PrductArea(string code = "general", int type = 1, int page = 0)
        {
            try
            {
                int areacode = 1;
                //code : general 普通 groupbuy 团购 exchange 积分兑换
                //type 1 普通 2 限时特卖 3 特别推荐

                switch (code.ToUpper())
                {
                    case "GENERAL":
                        if (type == 1 || type == 2 || type == 3)
                        {
                            ViewBag.productList = ProductBiz.GetProductListByAreaCode(1, type, page, 28);
                            areacode = 1;

                        }
                        else
                        {
                            ViewBag.Message = "指定商品区不存在，请选择其他区域。";
                            return View("../Home/error");
                        }

                        break;
                    case "GROUPBUY":
                        ViewBag.productList = ProductBiz.GetProductListByAreaCode(2, type, page, 28);
                        areacode = 2;
                        break;
                    case "EXCHANGE":
                        ViewBag.productList = ProductBiz.GetProductListByAreaCode(3, type, page, 28);
                        areacode = 3;
                        break;
                    default:
                        //ViewBag.productList = ProductBiz.GetProductListByAreaCode(1, 2, page, 28);
                        ViewBag.Message = "指定商品区不存在，请选择其他区域。";
                        return View("../Home/error");

                }
                ViewBag.areaCode = areacode;
                ViewBag.Type = type;
                if (areacode == 2)
                {
                    return View("GroupBuy");
                }
                return View();
            }
            catch
            {
                ViewBag.Message = "指定商品区不存在，请选择其他区域。";
                return View("../Home/error");
            }
        }

        public ActionResult GeneralProductArea(int category = 0, int subCategory = 0, int page = 0)
        {
            if (category == 0 && subCategory == 0)
            {
                return Redirect("/Shop/PrductArea?code=general&type=1");
            }
            else
            {
                ViewBag.productList = ProductBiz.GetProductListByCategory(category, subCategory, page, 28);

                var productSubCategory = new ProductCategory().Find(subCategory.ToString());
                ViewBag.productCategory = productSubCategory != null ? productSubCategory.CategoryName : "";

                var productcategory = new ProductCategory().Find(category.ToString());
                ViewBag.productCategory = productcategory != null ? productcategory.CategoryName : "";
                return View();
            }
        }
        #endregion

        #region 快餐区
        public ActionResult FastFood(int page = 0)
        {
            ViewBag.Business = BusinessBiz.GetAllBusinessByWhere(page, 30, "", "home");

            return View();
        }

        public ActionResult FastFoodBusiness(int d, int page = 0)
        {
            ViewBag.Business = new Business().Find(d.ToString());
            ViewBag.ProductList = ProductBiz.GetAllProducts("", 10, page, 30, d, "home");
            return View();
        }

        public ActionResult FastFoodDetail(int d = 0)
        {
            Product product = new Product().Find(d.ToString());
            ViewBag.Product = product;
            if (product != null)
            {
                ViewBag.Business = new Business().Find(product.BusinessId.ToString());
            }
            ViewBag.saleRecord = OrderBiz.GetSaleRecordByProductId(d, 0, 20);//商品交易记录
            ViewBag.appraiselist = AppraiseBiz.GetAppraiseListByProductId(d, 0, 20);//获取上平评价记录
            ViewBag.AreaCode = (int)product.AreaCode;
            ViewBag.Ploicy = new Policy().Find(c => c.ProductId == product.Id);//获取默认政策价格


            ViewBag.IsUnderstock = true;

            //判断是否显示评价按钮
            var IsViewAppriaseBtn = 0;
            if (OrderBiz.IsHasAppraise(product.Id))
            {
                IsViewAppriaseBtn = 1;
            }
            ViewBag.IsViewAppriaseBtn = IsViewAppriaseBtn;

            double totalAppraise = 5.0d;
            var Appraises = new Appraise().FindAll(c => c.ProductId == d && c.State == 1);
            if (Appraises != null && Appraises.Any())
            {
                totalAppraise = Appraises.Average(c => c.AppraiseGrade);
            }
            ViewBag.totalAppraise = Math.Round(totalAppraise, 1);
            string Satisfaction = "100%";
            var googdAppriase = new Appraise().Count(c => c.ProductId == d && c.State == 1 && c.AppraiseGrade >= 2);
            var allApprise = new Appraise().Count(c => c.ProductId == d && c.State == 1);
            if (allApprise != 0)
            {
                Satisfaction = Math.Round(googdAppriase * 1.0 / allApprise, 4) * 100 + "%";
            }
            ViewBag.Satisfaction = Satisfaction;

            ViewBag.Satisfaction = Satisfaction;
            int DelAuthenticate = 0;
            bool role = true;
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                string name = System.Web.HttpContext.Current.User.Identity.Name;
                var user = new User().Find(name);
                if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.CollegeAdmin)
                {
                    DelAuthenticate = 1;
                }
                if (user.SystemRole != UserRole.Member)
                {
                    role = false;
                }

            }
            ViewBag.Role = role;
            ViewBag.DelAuthenticate = DelAuthenticate;

            return View();
        }

        #endregion

        #region 用户中心点击支付跳转
        public ActionResult PayOrderForUserCenter(int id, int code)
        {
            var order = new Order().Find(id.ToString());
            
            ViewBag.Order = order;
            ViewBag.areaCode = code;
            return View("PayOrder");
        }
        #endregion

        #region 套餐区

        public ActionResult PackagesProducts(int page = 0)
        {
            ViewBag.PackagesProducts = ProductBiz.GetAllProductsByPackages("", 4, page, 30, "home");

            return View();
        }


        public ActionResult PackagesProductsDetail(int id = 0)
        {
            try
            {
                var product = ProductBiz.GetProductByIdForView(id, 4);//获取商品信息，包含一级分类

                product.SaleCount = OrderBiz.GetProductSaleCount(product.Id);
                product.Integral = Convert.ToInt32(product.policy.Price * SupportBiz.GetCostRank());
                ViewBag.productiId = product.Id;
                ViewBag.product = product;

                ViewBag.saleRecord = OrderBiz.GetSaleRecordByProductId(id, 0, 20);//商品交易记录
                ViewBag.appraiselist = AppraiseBiz.GetAppraiseListByProductId(id, 0, 20);//获取上平评价记录
                ViewBag.AreaCode = (int)product.AreaCode;

                int productRemain = ProductBiz.GetProductRemain(id);
                ViewBag.IsUnderstock = true;
                ViewBag.ProductRemain = productRemain;
                product.TotalRemain = productRemain;
                //判断是否显示评价按钮
                var IsViewAppriaseBtn = 0;
                if (OrderBiz.IsHasAppraise(product.Id))
                {
                    IsViewAppriaseBtn = 1;
                }
                ViewBag.IsViewAppriaseBtn = IsViewAppriaseBtn;

                double totalAppraise = 5.0d;
                var Appraises = new Appraise().FindAll(c => c.ProductId == id && c.State == 1);
                if (Appraises != null && Appraises.Any())
                {
                    totalAppraise = Appraises.Average(c => c.AppraiseGrade);
                }
                ViewBag.totalAppraise = Math.Round(totalAppraise, 1);
                string Satisfaction = "100%";
                var googdAppriase = new Appraise().Count(c => c.ProductId == id && c.State == 1 && c.AppraiseGrade >= 2);
                var allApprise = new Appraise().Count(c => c.ProductId == id && c.State == 1);
                if (allApprise != 0)
                {
                    Satisfaction = Math.Round(googdAppriase * 1.0 / allApprise, 4) * 100 + "%";
                }
                ViewBag.Satisfaction = Satisfaction;

                int userRole = 1;
                int DelAuthenticate = 0;
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    string username = System.Web.HttpContext.Current.User.Identity.Name;
                    var user = new User().Find(username);
                    userRole = (int)user.SystemRole;
                    if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.CollegeAdmin)
                    {
                        DelAuthenticate = 1;
                    }
                }
                ViewBag.DelAuthenticate = DelAuthenticate;
                ViewBag.userRole = userRole;


                return View();
            }
            catch
            {
                ViewBag.Message = "指定的商品未找到。请重新选择您所需要的商品";
                return View("../Home/error");
            }
        }
        #endregion
    }
}
